const Service = require('./index')
const articleModel = require('@/models/article.model')

class ArticleService extends Service {
  /**
   * 文章分页查询
   * @param {*} pageNo
   * @param {*} pageSize
   * @param {*} articleTitle
   * @param {*} status
   * @param {*} nickname
   */
  async findPage (pageNo = 1, pageSize = 20, searchKeywords, status) {
    try {
      const { list, total } = await articleModel.findPage({
        pageNo,
        pageSize,
        andConditions: {
          equal: {
            'arc.status': status
          }
        },
        orConditions: {
          like: {
            'arc.articleTitle': searchKeywords,
            'user.nickname': searchKeywords
          }
        }
      })
      return this.skipPage(list.map(item => {
        return {
          ...item,
          html: null,
          content: null
        }
      }), total, pageNo, pageSize)
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 删除文章
   * @param {*} articleId
   * @returns
   */
  async delete (articleId) {
    try {
      const exist = await articleModel.exist(articleId)
      if (!exist) {
        return {
          errorMessage: '文章不存在'
        }
      }
      await articleModel.delete(articleId)
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 文章审核
   * @param {*} articleId
   * @param {*} status
   * @returns
   */
  async approve (articleId, status) {
    if (status !== '2' && status !== '3') {
      return {
        errorMessage: '更新status状态值不正确'
      }
    }
    try {
      const exist = await articleModel.exist(articleId)
      if (!exist) {
        return {
          errorMessage: '文章不存在'
        }
      }
      await articleModel.updateStatus(articleId, status)
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new ArticleService()
